<template>
  <el-dialog v-model="dialogVisible" title="新建书籍" width="400px" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false" center align-center destroy-on-close>
    <el-form ref="ruleFormRef" :model="bookForm" :rules="rules" label-width="60px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="bookForm.name" placeholder="请输入书籍名称" maxlength="15" :show-word-limit="true" />
      </el-form-item>
      <el-form-item label="类型" prop="genre">
        <el-select v-model="bookForm.genre" placeholder="请选择书籍类型" style="width: 100%">
          <el-option v-for="item in genreOptions" :key="item.value" :label="item.label" :value="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="简介" prop="summary">
        <el-input v-model="bookForm.summary" type="textarea" placeholder="请输入书籍简介" maxlength="200" :rows="5" :show-word-limit="true" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onCancel(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="onSubmit(ruleFormRef)">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
/**
 * 创建书籍弹框组件
 */
import { ref, reactive, watch, toRaw } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useGlobalStore } from "@/store/modules/globalStore";
import { useVModel } from "@vueuse/core";

const globalStore = useGlobalStore();

interface Props {
  visible: boolean;
  editBook: any;
}
const props = withDefaults(defineProps<Props>(), {
  visible: false,
  editBook: {}
});
const emit = defineEmits(["update:visible", "onCreatedBook"]);
const dialogVisible = useVModel(props, "visible", emit);

const ruleFormRef = ref<FormInstance>();
// 新建书籍表单内容
const bookForm = reactive({
  name: "",
  genre: "",
  summary: ""
});
// 校验书名
const validateName = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入书籍名称"));
  } else if (value.length > 15) {
    callback(new Error("名称限制15个字"));
  } else {
    callback();
  }
};
// 校验类型
const validateGenre = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请选择书籍类型"));
  } else {
    callback();
  }
};
// 校验简介
const validateSummary = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入书籍简介"));
  } else if (value.length > 200) {
    callback(new Error("简介限制200个字"));
  } else {
    callback();
  }
};
// 表单校验规则
const rules = reactive<FormRules>({
  name: [{ validator: validateName, trigger: "blur" }],
  genre: [{ validator: validateGenre, trigger: "blur" }],
  summary: [{ validator: validateSummary, trigger: "blur" }]
});

// 书籍类型可选项
const genreOptions = [
  {
    value: "wuxia",
    label: "武侠"
  },
  {
    value: "xianxia",
    label: "仙侠"
  },
  {
    value: "xuanhuan",
    label: "玄幻"
  },
  {
    value: "qihuan",
    label: "奇幻"
  },
  {
    value: "yanqing",
    label: "言情"
  },
  {
    value: "dushi",
    label: "都市"
  },
  {
    value: "kehuan",
    label: "科幻"
  },
  {
    value: "xuanyi",
    label: "悬疑"
  },
  {
    value: "lingyi",
    label: "灵异"
  },
  {
    value: "lishi",
    label: "历史"
  },
  {
    value: "junshi",
    label: "军事"
  },
  {
    value: "youxi",
    label: "游戏"
  },
  {
    value: "tiyu",
    label: "体育"
  },
  {
    value: "tongren",
    label: "同人"
  },
  {
    value: "juben",
    label: "剧本"
  },
  {
    value: "duanpian",
    label: "短篇"
  },
  {
    value: "xianshi",
    label: "现实"
  },
  {
    value: "qita",
    label: "其他"
  }
];

watch(
  () => props.visible,
  (e) => {
    if (e && props.editBook.name) {
      bookForm.name = props.editBook.name;
      bookForm.genre = props.editBook.genre;
      bookForm.summary = props.editBook.summary;
    } else {
      bookForm.name = "";
      bookForm.genre = "";
      bookForm.summary = "";
    }
  }
);

// 点击取消
const onCancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogVisible.value = false;
};
// 点击确认
const onSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      // 如果editBook有值，说明是编辑书籍，否则，创建书籍
      if (props.editBook.name) {
        const oldPath = `${globalStore.workPath}/${props.editBook.genre}/${props.editBook.name}`;
        const newPath = `${globalStore.workPath}/${bookForm.genre}/${bookForm.name}`;
        window.electronAPI.updateBook(oldPath, newPath, toRaw(bookForm)).then((res) => {
          if (res) {
            onCancel(ruleFormRef.value);
            emit("onCreatedBook", true);
          }
        });
      } else {
        window.electronAPI.createBookDir(globalStore.workPath, toRaw(bookForm)).then((res) => {
          if (res) {
            onCancel(ruleFormRef.value);
            emit("onCreatedBook", true);
          }
        });
      }
    } else {
      return false;
    }
  });
};
</script>

<style scoped></style>
